package org.vidyakiran.app.server.dao.impl;

import javax.persistence.EntityExistsException;
import javax.persistence.EntityManager;

import org.springframework.stereotype.Repository;
import org.vidyakiran.app.server.dao.OrganisationDetailDao;
import org.vidyakiran.app.server.dao.util.DatabaseUtils;
import org.vidyakiran.app.server.domain.entity.Organisation;

import com.google.appengine.api.datastore.Key;


@Repository
public class OrganisationDetailDaoJpaImpl implements OrganisationDetailDao {

	EntityManager em;
	
	@Override
	public Organisation findOrgById(Key orgId) {
		em = DatabaseUtils.startTransaction(em);
		
		Organisation organisation;
		try {
			organisation = em.find(Organisation.class, orgId);
			//Get the child objects
			organisation.getAddress();
			organisation.getContacts();
						
			em.getTransaction().commit();
		} finally {
			DatabaseUtils.cleanupTransaction(em);
		}
		return organisation;
	}

	@Override
	public Organisation saveOrUpdateOrgDetails(Organisation organisation) {
		em = DatabaseUtils.startTransaction(em);
		
		try {
			em.persist(organisation);
			em.getTransaction().commit();
		} catch (EntityExistsException ex) {
			organisation = em.merge(organisation);
			em.getTransaction().commit();
		} finally {
			DatabaseUtils.cleanupTransaction(em);
		}
		return organisation;
	}
}
